package cn.kgc.springmvc.upload;

import cn.kgc.springmvc.exception.UploadException;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author: mosin
 * @version: v1.0  2022/10/20
 * 文件上传
 */
@Controller
@RequestMapping("file")
public class FileUpload {

    @PostMapping("upload")
    public  String  upload (@RequestParam("file") MultipartFile multipartFile){

        //  实现文件上传  MultipartFile
        // 1.判定上传的文件是否为空
        boolean empty = multipartFile.isEmpty();
        if(empty){
            // 抛出异常   上传的文件不能为空
            throw  new UploadException("上传的文件不能为空");
        }else{
            // 获取文件名
            String originalFilename = multipartFile.getOriginalFilename();
            // 获取扩展名  a.jpg     jpg  png
            String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
            //  uuid
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 文件名称  uuid+ extension
            String fileName = uuid+"."+filenameExtension;
            //文件上传
            File file = new File("D:\\upload", fileName);

            try {
                multipartFile.transferTo(file);
                return "hello";
            } catch (IOException e) {
                e.printStackTrace();
                throw  new UploadException("文件上传失败");
            }

        }
    }

}
